package com.glacier.yuyuan.gen.webapp.service.impl;

import com.alibaba.druid.pool.DruidDataSource;
import com.glacier.yuyuan.gen.webapp.domain.GenDatasource;
import com.glacier.yuyuan.gen.webapp.mapper.GenDatasourceMapper;
import com.glacier.yuyuan.gen.webapp.service.DataSourceService;
import jakarta.annotation.PreDestroy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * date 2023-02-01 22:02
 *
 * @author glacier
 * @version 1.0.0
 */
@Service
public class DataSourceServiceImpl implements DataSourceService {
    private static final Logger LOGGER = LoggerFactory.getLogger(DataSourceServiceImpl.class);

    /**
     * 保存数据源
     */
    private static final Map<String, DruidDataSource> DATA_SOURCE_MAP = new ConcurrentHashMap<>(16);

    private GenDatasourceMapper genDatasourceMapper;

    @Autowired
    public void setGenDatasourceMapper(GenDatasourceMapper genDatasourceMapper) {
        this.genDatasourceMapper = genDatasourceMapper;
    }

    /**
     * 获取数据源
     *
     * @param sourceId
     * @return
     */
    @Override
    public DruidDataSource getDataSource(String sourceId) {
        if (DATA_SOURCE_MAP.containsKey(sourceId)) {
            return DATA_SOURCE_MAP.get(sourceId);
        }
        GenDatasource genDatasource = this.genDatasourceMapper.findById(sourceId);
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl(genDatasource.getUrl());
        dataSource.setUsername(genDatasource.getUsername());
        dataSource.setPassword(genDatasource.getPassword());

        DATA_SOURCE_MAP.put(sourceId, dataSource);
        return dataSource;
    }

    @PreDestroy
    public void preDestroy() {
        // 关闭
        for (Map.Entry<String, DruidDataSource> sourceEntry : DATA_SOURCE_MAP.entrySet()) {
            DruidDataSource dataSource = sourceEntry.getValue();
            if (dataSource != null) {
                dataSource.close();
            }
        }
    }
}
